require 'rubygems'
require 'watir'
require 'miscfunc'

class Login
    include MiscFunc

    def initialize
        @ie_for_kaixin = Watir::IE.start("http://www.kaixin001.com/")
        info "Open the IE with homepage of kaixin001"
        if !File.exist?(".tmp")
          Dir.mkdir(".tmp")
        end
    end

    def login_to_kaixin_with (name, password)
        info "login to kaixin with #{name}"
        begin
            #logout
            set_login_field('email', name)
            set_login_field('password', password)
            click_the_button_id_is('btn_dl')
        rescue => err
            error err
        end
        info "login successfully"
    end

    def set_login_field (field, value)
        @ie_for_kaixin.text_field(:name, field).set(value)
    end

    def click_the_button_id_is(name)
        @ie_for_kaixin.button(:id, name).click
    end

    def logout
        @ie_for_kaixin.goto 'http://www.kaixin001.com/login/logout.php'
        #Dir.glob(".tmp/*.html").each do |file|
        #  if File.delete("#{file}")
        #    info "#{file} is deleted" 
        #  end         
        #end
        #if Dir.rmdir(".tmp")
        #  info ".tmp is deleted"
        #end
    end

    def quit
        @ie_for_kaixin.close
    end
end